﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Productionorderss;
using MyMES.Read.API.Dtos;
using MySqlX.XDevAPI.Common;
using System;

namespace MyMES.Read.API.Application.CommendHandlers.Productionorderss
{
    public class GetProductionorderssProcessCommendHandlers : IRequestHandler<GetProductionorderssProcessCommends, APIPaging<List<ProcessinfoDto>>>
    {

        private readonly IBaseRepository<Process> processRepository;
        private readonly IBaseRepository<ProcessInfo> processinfoRepository;
        private readonly IMapper mapper;

        public GetProductionorderssProcessCommendHandlers(IBaseRepository<Process> processRepository, IBaseRepository<ProcessInfo> processinfoRepository, IMapper mapper)
        {
            this.processRepository = processRepository;
            this.processinfoRepository = processinfoRepository;
            this.mapper = mapper;
        }



        /// <summary>
        /// 获取工序流程
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<ProcessinfoDto>>> Handle(GetProductionorderssProcessCommends request, CancellationToken cancellationToken)
        {

            APIPaging<List<ProcessinfoDto>> result = new APIPaging<List<ProcessinfoDto>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";

            string sql = "select a.*,b.ProcessCode FROM process a  LEFT JOIN processinfo b on a.ProcessInfoId=b.ProcessInfoId   ";

            var process= processRepository.SelectAsync(sql).Result;
            var processinfo= processinfoRepository.SelectAsync(sql).Result;

            var proce=mapper.Map<List<ProcessinfoDto>>(process);
            var proceinfo=mapper.Map<List<ProcessinfoDto>>(processinfo);

            foreach (var item in proce)
            {
                item.ProcessCode = proceinfo.Where(x => x.ProcessInfoId == item.ProcessInfoId).FirstOrDefault()?.ProcessCode;
            }
            result.TotalCount = proce.Count;
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            proce = proce.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.data = proce;
            return result;
        }
    }
}
